#! /bin/bash 

work_dir="/usr/local"

#增加输入参数 
#参数1 值含义
# 1:启动ng 
# 2:启动ws
# 3:启动ng+ws
# 无输入参数默认启动ng+ws

StartFlag=3
if [ $# == 0 ];then
	echo "use default setting start nginx and ws proxy"
else
	if [ $1 == 1 ];then
        echo "setting start nginx proxy"
    elif [ $1 == 2 ];then
        echo "setting start ws proxy"
    elif [ $1 == 3 ];then
        echo "setting start nginx and ws proxy"
    else
        echo "if input para, the first para must be 1 or 2 or 3 \n
        1:setting start nginx proxy\n
        2:setting start ws proxy\n
        3:setting start nginx and ws proxy\n
        no para:default setting start nginx and ws proxy\n
        exit"

        exit 1
    fi

    StartFlag=$1
fi

function f_kill_nginx() {

    # 杀掉nginx僵尸进程
    list_wpids=$(ps axw -o pid,ppid,user,command | grep nginx | grep 'worker process' | grep -v grep | awk '{if($2=='1'){print $1}}')
    if [ -n "$list_wpids" ]; then
        for _workpid in $list_wpids; do
            echo "kill nginx worker process, pid:" ${_workpid}
            kill -9 ${_workpid}
        done
    fi

    list_mpids=$(ps -aux | grep $1 | grep 'master process' | grep -v grep | awk '{print $2}')
    for _masterpid in ${list_mpids}; do
        list_wpids=$(ps axw -o pid,ppid,user,command | grep nginx | grep 'worker process' | grep -v grep | awk '{if($2=='${_masterpid}'){print $1}}')
        if [ -n "$list_wpids" ]; then
            for _workpid in $list_wpids; do
                echo "kill nginx worker process, pid:" ${_workpid}
                kill -9 ${_workpid}
            done
        fi
        echo "kill nginx master process, pid:" ${_masterpid}
        kill -9 ${_masterpid}
    done
}
 
ng_cmd='/usr/sbin/nginx'
ng_arg_mpc='-c '${work_dir}'/rongan/conf/nginx.conf.mpc'
ws_cmd='bash '${work_dir}'/rongan/bin/service/start_tcpws_mpc.sh'
ws_arg_mpc='-c '${work_dir}'/rongan/conf/tcpws.yaml'


if [ $StartFlag == 2 ] || [ $StartFlag == 3 ];then
    echo "start ws proxy"

    echo $ws_cmd
    echo $ws_arg_mpc
    ${ws_cmd} ${ws_arg_mpc}
fi

if [ $StartFlag == 1 ] || [ $StartFlag == 3 ];then
    echo "start nginx proxy"

    if [ -f "${ng_cmd}" ]; then
        f_kill_nginx /rongan/conf/nginx.conf
        sleep 1s
        ${ng_cmd} ${ng_arg_mpc}
    else
        echo ${ng_cmd} ":No such command"
        exit 1
    fi
fi
